package com.flaremars.picker;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.flaremars.picker.constants.ProjectConstants;
import com.flaremars.picker.fragments.PicturePreTreatmentFragment;
import com.flaremars.picker.utils.StringUtils;
import com.flaremars.picker.utils.http.newhttp.HttpUploadHelper;
import com.flaremars.picker.utils.http.newhttp.ProgressListener;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PreTreatmentActivity extends AppCompatActivity {

    private static final String URL_UPLOAD = ProjectConstants.BASE_URL + "file/upload";
    public static final String ARGUMENT_PICTURE_PATH = "picture_path";
    public static final String ARGUMENT_NEED_ROTATE = "need_rotate";

    private MaterialDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_pretreatment);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        String picturePath = getIntent().getStringExtra(ARGUMENT_PICTURE_PATH);
        boolean needRotate = getIntent().getBooleanExtra(ARGUMENT_NEED_ROTATE,false);
        getSupportFragmentManager().beginTransaction().replace(R.id.container, PicturePreTreatmentFragment.newFragment(picturePath,needRotate)).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_pre_treatment, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
//            startActivity(new Intent(this,SettingsActivity.class));
            return true;
        } else if (id == R.id.action_upload) {
            String targetFilePath = "";
            try {
                targetFilePath = getContentFragment().saveBitmap();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (!StringUtils.INSTANCE.isEmpty(targetFilePath)) {
                startUpload(new File(targetFilePath));
            } else {
                showToast("无可用图片，请先进行图片采集");
            }
            return true;
        } else if (id == android.R.id.home) {
            startActivity(new Intent(this, MainActivity.class));
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void startUpload(final File targetFile) {
        if (!targetFile.exists()) {
            showToast("文件不存在!");
            return;
        }

        new MaterialDialog.Builder(this).
                title("图片上传中...").
                contentGravity(GravityEnum.CENTER).
                progress(false, (int) targetFile.length(), true).
                showListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {
                        progressDialog = (MaterialDialog) dialog;
                        progressDialog.setCanceledOnTouchOutside(false);

                        HttpUploadHelper.INSTANCE.addUploadRequest(
                                URL_UPLOAD,new HashMap<String, String>(), "file", targetFile,
                                new ProgressListener() {
                                    @Override
                                    public void onProgress(long progress, long total, boolean done) {
                                        if (done) {
                                            dismissDialog();
                                        } else {
                                            progressDialog.setProgress((int)progress);
                                        }
                                    }
                                }, new Callback() {
                                    @Override
                                    public void onFailure(Call call,final IOException e) {
                                        dismissDialog();
                                        Log.e("tag", e.getMessage());
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                showToast(e.getMessage());
                                            }
                                        });
                                        e.printStackTrace();
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) {
                                        dismissDialog();
                                        try {
                                            handleResponse(response);
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }
                }).
                show();
    }

    private PicturePreTreatmentFragment getContentFragment() {
        return (PicturePreTreatmentFragment) getSupportFragmentManager().getFragments().get(0);
    }

    private void showToast(String message) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }

    //todo the core code for parse the result
    private void handleResponse(Response response) throws IOException {
        final String responseBody = response.body().string();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(responseBody);
            }
        });
    }

    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
